package com.gla.giliair.web.admin;

import com.gla.giliair.entity.Customer;
import com.gla.giliair.entity.MOrder;
import com.gla.giliair.entity.Seat;
import com.gla.giliair.util.EmailUtil;
import com.gla.giliair.util.MapGenerator;
import com.gla.giliair.util.PatternUtil;
import com.gla.giliair.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Author: Yingtian qian
 * @Date: 2021/8/25 20:38
 */
@Api(tags = "订单管理模块")
@RestController
@RequestMapping("/api/admin")
public class AdminOrderController extends BaseController {
    @ApiOperation(value = "获取统计数据(订单总数、航班总数、用户总数)", notes = "获取统计数据(订单总数、航班总数、用户总数)", produces = "application/json")
    @GetMapping("/getCount")
    @ResponseBody
    public Map<String, Object> getCount() {
        return orderService.getCount();
    }

    @ApiOperation(value = "根据身份证号查询订单信息列表", notes = "根据身份证号、单个或多个状态码，查询订单信息列表", produces = "application/json")
    @GetMapping("/findOrderByIDNumber")
    @ResponseBody
    public Map<String, Object> findOrderByIDNumber(@RequestParam("IDNumber") String IDNumber,
                                                   //订单状态默认值为空，表示查询全部订单；其他值表示查询相应状态的订单，可传多个状态码进行合并查询；无效状态码会被忽略
                                                   //状态码：0->待付款；1->已付款，未选座；2->已选座；3->已出票；-1->用户取消；-2->用户退票；-3->管理员关闭；-4->超时取消；-5->用户申请退票
                                                   @RequestParam(value = "state", required = false) Integer[] states,
                                                   @RequestParam(value = "page", defaultValue = "1") Integer page,
                                                   @RequestParam(value = "pageSize", defaultValue = "16") Integer pageSize) {
        if (!StringUtils.hasText(IDNumber)) {
            return MapGenerator.getRes(500, "请输入乘机人身份证号！");
        }
        if (!PatternUtil.isIdentity(IDNumber)) {
            return MapGenerator.getRes(501, "乘机人身份证号格式有误！");
        }
        List<Integer> stateList = null;
        if (states != null) {
            stateList = new ArrayList<>();
            for (Integer state : states) {
                if (state == 0 || state == 1 || state == 2 || state == 3 || state == -1 || state == -2 || state == -3 || state == -4 || state == -5) {
                    stateList.add(state);
                }
            }
        }
        return orderService.findOrdersByIDNumberAndStates(IDNumber, stateList, page, pageSize);
    }

    @ApiOperation(value = "查询订单信息列表", notes = "根据单个或多个状态码，查询订单信息列表；或者直接查询全部订单列表", produces = "application/json")
    @GetMapping("/findOrder")
    @ResponseBody
    public Map<String, Object> findOrder(//订单状态默认值为空，表示查询全部订单；其他值表示查询相应状态的订单，可传多个状态码进行合并查询；无效状态码会被忽略
                                         //状态码：0->待付款；1->已付款，未选座；2->已选座；3->已出票；-1->用户取消；-2->用户退票；-3->管理员关闭；-4->超时取消；-5->用户申请退票
                                         @RequestParam(value = "state", required = false) Integer[] states,
                                         //排序关键词：orderId、orderNumber、
                                         // flightId、flightNumber、leavePoint、arrivePoint、leaveAirport、arriveAirport、leaveTime、arriveTime、flightDuration、
                                         // IDNumber、realname、phone、birthday、contacts、contactsPhone、
                                         // companyId、companyName、planemodelId、planemodelName、
                                         // seatId、seatType、seatNumber、
                                         // customerId、discountType1、discountType2、originalPrice、price、
                                         // paymentType、orderState、
                                         // createTime、updateTime、isDeleted
                                         //不填关键词默认按id逆向排序
                                         @RequestParam(value = "sort", defaultValue = "orderId") String sort,
                                         //正反序只对关键词生效
                                         @RequestParam(value = "isASC", defaultValue = "false") boolean isASC,
                                         @RequestParam(value = "page", defaultValue = "1") Integer page,
                                         @RequestParam(value = "pageSize", defaultValue = "16") Integer pageSize) {
        List<Integer> stateList = null;
        if (states != null) {
            stateList = new ArrayList<>();
            for (Integer state : states) {
                if (state == 0 || state == 1 || state == 2 || state == 3 || state == -1 || state == -2 || state == -3 || state == -4 || state == -5) {
                    stateList.add(state);
                }
            }
        }
        return orderService.findOrdersByStates(stateList, sort, isASC, page, pageSize);
    }

    @ApiOperation(value = "修改订单状态", notes = "修改订单状态；若要关闭订单，前端需传入状态码为-3，并根据返回的status覆写返回json的msg", produces = "application/json")
    @PostMapping("/modifyOrder")
    @ResponseBody
    public Map<String, Object> modifyOrder(@RequestParam("orderId") Long orderId,
                                           //状态码：0->待付款；1->已付款，未选座；2->已选座；3->已出票；-1->用户取消；-2->用户退票；-3->管理员关闭；-4->超时取消；-5->用户申请退票
                                           @RequestParam("state") Integer state) {
        if (orderId == null) {
            return MapGenerator.getRes(500, "请输入订单id！");
        }
        if (state != 0 && state != 1 && state != 2 && state != 3 && state != -1 && state != -2 && state != -3 && state != -4 && state != -5) {
            return MapGenerator.getRes(501, "不存在该订单状态！");
        }
        MOrder mOrder = new MOrder();
        mOrder.setOrderId(orderId);
        mOrder.setOrderState(state);
        return orderService.modifyOrder(mOrder);
    }

    @ApiOperation(value = "管理员关闭订单", notes = "管理员关闭订单", produces = "application/json")
    @PostMapping("/closeOrder")
    @ResponseBody
    public Map<String, Object> closeOrder(@RequestParam("orderId") Long orderId) {
        if (orderId == null) {
            return MapGenerator.getRes(500, "请输入订单id！");
        }
        MOrder mOrder = new MOrder();
        mOrder.setOrderId(orderId);
        mOrder.setOrderState(-3);

        Map<String, Object> res = orderService.modifyOrder(mOrder);
        if ((Integer) res.get("status") == 200) {
            return MapGenerator.getRes(200, "关闭订单成功!");
        }
        return res;
    }

    @ApiOperation(value = "管理员出票", notes = "管理员出票", produces = "application/json")
    @PostMapping("/printTicket")
    @ResponseBody
    public Map<String, Object> printTicket(@RequestParam("orderId") Long orderId) {
        if (orderId == null) {
            return MapGenerator.getRes(500, "请输入订单id！");
        }

        Map<String, Object> res = orderService.printTicket(orderId);
        if ((Integer) res.get("status") == 200) {
            MOrder mOrderParam = (MOrder) res.get("data");
            Customer user = userService.selectCustomerById(mOrderParam.getCustomerId());
            String email = user.getEmail();

            if (StringUtils.hasText(email)) {
                String msg = "亲爱的客户" + user.getNickname() + "，您的" +
                        mOrderParam.getLeavePoint() + "-" + mOrderParam.getArrivePoint() +
                        "航班订单已成功出票，感谢您的使用！";
                EmailUtil.sendEmail(msg, "出票成功", email);
            }
        }
        return res;
    }

    @ApiOperation(value = "管理员审核申请退票", notes = "管理员审核申请退票", produces = "application/json")
    @PostMapping("/modifyApplyRefund")
    @ResponseBody
    public Map<String, Object> modifyApplyRefund(@RequestParam("orderId") Long orderId,
                                                 //不填是否通过审核，默认通过审核
                                                 @RequestParam(value = "isOK", defaultValue = "true") boolean isOK,
                                                 //不填未通过审核是否关闭订单，默认不关闭
                                                 @RequestParam(value = "isClosed", defaultValue = "false") boolean isClosed,
                                                 //原因
                                                 @RequestParam(value = "reason", required = false) String reason,
                                                 //退款金额，不填退全款
                                                 @RequestParam(value = "amount", required = false) BigDecimal amount) {
        if (orderId == null) {
            return MapGenerator.getRes(500, "请输入订单id！");
        }
        MOrder mOrderFromDB = orderService.selectOrderById(orderId);
        if (mOrderFromDB == null) {
            return MapGenerator.getRes(502, "订单不存在！");
        }
        if (mOrderFromDB.getOrderState() != -5) {
            return MapGenerator.getRes(503, "订单状态不为用户申请退款，不能审核！");
        }
        BigDecimal allAmount = mOrderFromDB.getPrice();
        boolean isAll = true;
        if (amount != null) {
            if (amount.compareTo(allAmount) > 0) {
                return MapGenerator.getRes(504, "选定退款金额大于用户全额，不能退款！");
            }
            isAll = false;
            allAmount = amount;
        }
        MOrder mOrder = new MOrder();
        mOrder.setOrderId(orderId);
        if (isOK) {
            mOrder.setOrderState(-2);
        } else {
            if (isClosed) {
                mOrder.setOrderState(-3);
            }
        }
        Map<String, Object> res = orderService.modifyOrder(mOrder);
        if ((Integer) res.get("status") == 200) {
            MOrder mOrderParam = (MOrder) res.get("data");
            Customer user = userService.selectCustomerById(mOrderParam.getCustomerId());
            String email = user.getEmail();
            if (isOK) {
                if (StringUtils.hasText(reason)) {
                    alipayService.refund(mOrderParam.getOrderNumber(), String.valueOf(allAmount), reason, isAll);
                } else {
                    alipayService.refund(mOrderParam.getOrderNumber(), String.valueOf(allAmount), "退款申请通过", isAll);
                }
                if (StringUtils.hasText(email)) {
                    String msg = "亲爱的客户" + user.getNickname() + "，您的" +
                            mOrderParam.getLeavePoint() + "-" + mOrderParam.getArrivePoint() +
                            "航班订单申请退款已被通过";
                    msg += "，退款金额：";
                    msg += allAmount;
                    if (StringUtils.hasText(reason)) {
                        msg += "，原因：";
                        msg += reason;
                    }
                    msg += "，感谢您的使用！";
                    EmailUtil.sendEmail(msg, "申请退款成功", email);
                }
            } else {
                if (StringUtils.hasText(email)) {
                    String msg = "亲爱的客户" + user.getNickname() + "，您的" +
                            mOrderParam.getLeavePoint() + "-" + mOrderParam.getArrivePoint() +
                            "航班订单申请退款未被通过";
                    if (StringUtils.hasText(reason)) {
                        msg += "，未通过原因：";
                        msg += reason;
                    }
                    msg += "，请联系工作人员！";
                    EmailUtil.sendEmail(msg, "申请退款失败", email);
                }
            }
            return MapGenerator.getRes(200, "处理用户退票申请成功!");
        }
        return res;
    }
}
